
#include "apue.h"
#include <sys/socket.h>

#define MAXSLEEP 128

int connect_retry(int sockfd, const struct sockaddr *addr, socklen_t alen)
{
    // Try to connect with exponential banckoff
    for (int numsec = 0; numsec < MAXSLEEP; numsec++)
    {
        if (connect(sockfd, addr, alen) == 0)
        {
            // connect accepted
            return 0;
        }

        // Delay before trying again
        if (numsec <= MAXSLEEP/2)
        {
            sleep(numsec);
        }
    }

    return -1;
}
